import React, { Component } from 'react'
import {connect} from 'react-redux'
interface IProps{
    title:string,
    price:number,
    num:number,
    checked:boolean,
    id:number,
    changeNum:(id:number,num:number) => void,
    open:(id:number) => void,
    changeChecked:(id:number,checked:boolean) => void
}

class CarProduct extends Component<IProps>{
    render() {
        let {title,price,num,checked,id} = this.props;
        return (
            <div>
                <input type="checkbox" checked={checked} onChange={() =>{
                    this.props.changeChecked(id,!checked);
                }}/>
                <div>
                    <h4>{title}</h4>
                    <span>{price}</span>
                </div>
                <div>
                    <button onClick={() => {this.count('-')}}>-</button>
                    <span>{num}</span>
                    <button onClick={() => {this.count('+')}}>+</button>
                </div>
            </div>
        )
    }

    //计算的函数
    count = (flag:string) => {
        let {num,id} = this.props;
        console.log(this.props)
        if(flag === '+'){
            //添加数量
            num++;
            this.props.changeNum(id,num);
        }else{
            //减去数量
            //1.大于1，直接减数量  2.等于1,出现弹窗
            if(num > 1){
                num--;
                this.props.changeNum(id,num);
            }else{
                //弹弹窗
                this.props.open(id);
            }
        }

    }

    change = () => {
        console.log("====")
    }
}

let stateMapToProps = () => {
    return {}
}

let dispatchMapToProps = (dispatch:any) => {
    return {
        //id:修改对象的id num：修改之后的值 
        changeNum:(id:number,num:number) => {
            console.log("==num=",num)
            dispatch({type:'CHANGE_NUM',num,id});
        },
        changeChecked(id:number,checked:boolean){
            dispatch({type:'CHANGE_CHECKED',id,checked})
        }
    }
}

export default connect(stateMapToProps,dispatchMapToProps)(CarProduct)
